
package sg.edu.nus.iss.cats.dataaccess.mysql;

import sg.edu.nus.iss.cats.model.*;
import sg.edu.nus.iss.cats.dataaccess.*;
import java.sql.*;

public class UserObjectHandler implements ObjectHandler {

    public String getTableName () {
        return DBConstants.usersTableName;
    }

    public String getKeyParameterConstraint () {
        return DBConstants.u_userId + "=?";
    }

    public void setKeyParameters (PreparedStatement statement, Object obj)
                   throws SQLException, DAOException {
        throw new DAOException ("Method setKeyValues not implemented");
    }

    public Object retrieveObject (ResultSet results)
                   throws SQLException, DAOException {
        User obj = new User ();
        obj.setUserId (results.getString(DBConstants.u_userId));
        obj.setName (results.getString(DBConstants.u_name));
        obj.setPassword (results.getString(DBConstants.u_password));
        obj.setEmployeeId (results.getString(DBConstants.u_employeeId));
        return obj;
    }

    public void insertKeys (ResultSet results, Object obj)
                   throws SQLException, DAOException {
        throw new DAOException ("Method insertKeys not implemented");
    }

    public void updateObject (ResultSet results, Object obj)
                   throws SQLException, DAOException {
        throw new DAOException ("Method updateObject not implemented");
    }

    public void completeObjectRetrieve (Object obj) throws DAOException {
        User user = (User) obj;
        SQLObjectManager mgr = new SQLObjectManager (
            new UserRoleObjectHandler ());
        mgr.setQueryConstraint (DBConstants.u_userId + "='" + user.getUserId() + "'");
        String[] results = (String[]) mgr.getObjects ();

        UserDAO userDAO = DAOFactory.getInstance().getUserDAO();
        for (int i = 0; i < results.length; i++) {
            String roleId = results[i];
            Role r = userDAO.findRole(roleId);
            if (r != null) {
                user.addRole (r);
            }
        }
    }

    public Object[] getObjectArray (int length) {
        return new User [length];
    }
}